<template>
  <div class="mapToolbar">
    <div class="mapToolbar-btnGroup">
      <ul id="nav">
        <li class="li-one-first">
          <a>
            <span class="kfb-icon-celiang3">测量</span>
          </a>
          <ul>
            <li class="li-two-first">
              <a @click="measureLength">
                <span class="kfb-icon-juli2">测距</span>
              </a>
            </li>
            <li class="li-two-second">
              <a @click="measurePolygon">
                <span class="kfb-icon-mianji">侧面</span>
              </a>
            </li>
            <li class="li-two-third">
              <a @click="measureClear">
                <span class="kfb-icon-shanchu1">清除</span>
              </a>
            </li>
          </ul>
        </li>
        <li class="li-one-middle" style="height: 34px">
          <a @click="appFullScreen">
            <span class="el-icon-full-screen">全屏</span>
          </a>
        </li>
        <li class="li-one-middle">
          <a @click="selectPrint">
            <span class="kfb-icon-dayin">打印</span>
          </a>
        </li>
        <li class="li-one-last">
          <a>
            <span class="kfb-icon-compared">分屏</span>
          </a>
          <ul>
            <li class="li-two-first">
              <a @click="singleScreen">
                <span class="kfb-icon-monitor-outline">单屏</span>
              </a>
            </li>
            <li class="li-two-second">
              <a @click="doubleScreen">
                <span class="kfb-icon-jingxiang">双屏</span>
              </a>
            </li>
            <li class="li-two-third">
              <a @click="swipeScreen">
                <span class="kfb-icon-duibi">卷帘</span>
              </a>
            </li>
          </ul>
        </li>
      </ul>
    </div>
    <map-print :map-print-visible="mapPrintVisible" @toggleMapPrint="toggleMapPrint" />
  </div>
</template>
<script>
import { mapState } from "vuex";
import { add, remove, update, list } from "@/api/bookmark";
import Clone from "@/utils/clone";
import { poiList, poiAddress } from "@/api/poi";
import { searchRiverByName } from "@/api/hzz/search";
import SmQuery from "@/assets/js/utils/SmQuery.js";
import BoxUtil from "@/assets/js/utils/BoxUtil.js";
import MapPrint from "@/pages/xcgl/components/mapPrint";
export default {
  name: "Index",
  data() {
    return {
      isVisible: 0,
      dialogFormVisible: false, // 对话框
      bookmarks: [], // 书签数据
      form: {}, // 书签表单
      isAdd: false,
      placeName: "",
      currentPage: 1,
      pageSize: 10,
      total: 0,
      poiData: [],
      mapPrintVisible: false
    };
  },
  components: {MapPrint},
  mounted() {
    //this.mapService.on("map.init", this.mapInitComplete, this);
  },
  methods: {
    /**
     * 取消打印
     */
    toggleMapPrint(val) {
      this.mapPrintVisible = false;
    },
    singleScreen() {
      this.$emit("onDoubleScreenSwitch", 2);
      this.comparable.setMode(2);
    },
    doubleScreen() {
      this.$emit("onDoubleScreenSwitch", 1);
      this.comparable.setMode(1);
    },
    swipeScreen() {
      this.$emit("onDoubleScreenSwitch", 0);
      this.comparable.setMode(0);
    },
    selectFeature($event) {
      this.riverIsSelectIcon === "kfb-icon-move-outline"
        ? (this.riverIsSelectIcon = "kfb-icon-checkmark-outline")
        : (this.riverIsSelectIcon = "kfb-icon-move-outline");
      this.$store.commit("hzzSys/setIsSelected", !this.isSelect);
    },
    /**
     * 选择底图
     */
    selectBaseMap($event) {
      this.isVisible = this.isVisible === 1 ? 0 : 1;
    },

    /**
     * 选择地图模块
     */
    selectMapModule() {
      this.isVisible = this.isVisible === 5 ? 0 : 5;
    },
    /**
     * 选择搜索
     */
    selectSearch() {
      this.isVisible = this.isVisible === 2 ? 0 : 2;
      if (this.isVisible) {
        this.$nextTick(() => {
          this.$refs["poi_input"].focus();
        });
      }
    },
    /**
     * 打印
     */
    selectPrint() {
      // const map = this.comparable.getMap();
      // var param = {
      //   style: map.getStyle(),
      //   center: map.getCenter(),
      //   zoom: map.getZoom()
      // };
      // const routeData = this.$router.resolve({
      //   path: "/printer",
      //   query: { opt: JSON.stringify(param) }
      // });
      // window.open(routeData.href, "_blank");
      this.mapPrintVisible = true;
      // window.print();
    },

    /**
     * 选择河湖搜索
     */
    selectRiverSearch() {
      this.isVisible = this.isVisible === 6 ? 0 : 6;
      if (this.isVisible) {
        this.$nextTick(() => {
          this.$refs["river_input"].focus();
        });
      }
    },

    /**
     * 选择测量
     */
    selectMeasure() {
      this.isVisible = this.isVisible === 3 ? 0 : 3;
    },

    /**
     * 选择书签
     */
    selectBookMark() {
      this.isVisible = this.isVisible === 4 ? 0 : 4;
      if (this.bookmarks.length > 0) {
        return;
      }
      this.getBookMarks();
    },

    /**
     * 选择基础底图
     * @param $event
     * @param item
     */
    checkBaseGroup($event, item) {
      if (item.checked) {
        return;
      }
      this.mapService.setBaseLayer(item.layers);
      this.baseMapGroup.forEach(group => {
        this.$set(group, "checked", group._id === item._id);
      });
    },
    /**
     * map style初始化完成函数
     */
    mapInitComplete() {
      if (this.isloadComplete) {
        this.mapService.setBaseLayer(this.baseLayers);
      }
      this.isloadComplete = true;
      this.baseMapGroup.forEach((group, i, array) => {
        this.$set(group, "checked", i === this.index);
      });
    },

    /**
     * 测量长度
     */
    measureLength() {
      this.measureSync.setDrawAction(0);
      // this.mapService.getMeasureTool().setDrawAction(0);
      // 三维量算
      // if (this.sceneViewer !== null) {
      //   if (this.sceneTool === null) {
      //   }
      //   this.sceneTool.measureDis();
      // }
    },
    /**
     * 测量面积
     */
    measurePolygon() {
      this.measureSync.setDrawAction(1);
      // this.mapService.getMeasureTool().setDrawAction(1);
      // 三维量算
      // if (this.sceneViewer !== null) {
      //   if (this.sceneTool === null) {
      //     this.sceneTool = new SceneTool(this.sceneViewer);
      //   }
      //   this.sceneTool.measureArea();
      // }
    },
    /**
     * 清除测量
     */
    measureClear() {
      // this.mapService.getMeasureTool().clearMeasure();
      this.measureSync.clearMeasure();
      // // 三维量算
      // if (this.sceneViewer !== null) {
      //   if (this.sceneTool === null) {
      //     this.sceneTool = new SceneTool(this.sceneViewer);
      //   }
      //   this.sceneTool.clearAll();
      // }
    },
    /**
     * 添加书签
     */
    addBookMark() {
      this.isAdd = true;
      this.dialogFormVisible = true;
      this.$nextTick(function() {
        this.$refs["book_input"].focus();
      });
      const map = this.comparable.getMap();
      const sceneViewer = this.sceneViewer;
      const mapModuleIndex = this.mapModuleIndex;
      if (mapModuleIndex === 0) {
        const camera = {
          center: map.getCenter(),
          zoom: map.getZoom(),
          bear: map.getBearing(),
          pitch: map.getPitch()
        };
        this.form = {
          uid: this.$store.getters.id,
          camera: camera,
          type: 0,
          name: ""
        };
      } else if (mapModuleIndex === 1) {
        const camera = {
          position: sceneViewer.camera.positionCartographic,
          heading: sceneViewer.camera.heading,
          pitch: sceneViewer.camera.pitch,
          roll: sceneViewer.camera.roll
        };
        this.form = {
          uid: this.$store.getters.id,
          camera: camera,
          type: 1,
          name: ""
        };
      } else if (mapModuleIndex === 2) {
        const camera = {
          center: map.getCenter(),
          zoom: map.getZoom(),
          bear: map.getBearing(),
          pitch: map.getPitch()
        };
        this.form = {
          uid: this.$store.getters.id,
          camera: camera,
          type: 0,
          name: ""
        };
      }
    },

    handleSizeChange(val) {},

    /**
     * 翻页
     * @param val
     */
    handleCurrentChange(val) {
      this.currentPage = val;
      this.requestPoiData();
    },

    /**
     * 翻页
     */
    handleCurrentChange_River(val) {
      this.currentPage_river = val;
      this.requestRiverData();
    },
    /**
     * 搜索按钮
     */
    poiSearch() {
      this.currentPage = 1;
      this.poiData = [];
      this.total = 0;
      this.requestPoiData();
    },

    /**
     * 河湖搜索时间点击
     */
    riverSearch() {
      this.currentPage_river = 1;
      this.pageSize_river = 10;
      this.total_river = 0;
      this.requestRiverData();
    },

    /**
     * 请求数据
     */
    requestPoiData() {
      poiList({
        keyWord: this.placeName,
        pageIndex: this.currentPage,
        pageSize: this.pageSize
      }).then(res => {
        this.total = res.data.tatol;
        this.poiData = res.data.data;
        if (this.total == 0) {
          this.$message({
            type: "info",
            message: "没有数据!"
          });
        }
      });
    },

    /**
     * 河湖数据搜索
     */
    requestRiverData() {
      searchRiverByName({
        keyWord: this.riverName,
        skip: (this.currentPage_river - 1) * this.pageSize_river,
        limit: this.pageSize_river
      }).then(res => {
        this.total_river = res.data.count;
        this.riverData = res.data.data;
        if (this.total_river == 0) {
          this.$message({
            type: "info",
            message: "没有数据!"
          });
        }
      });
    },

    /**
     * poi定位
     * @param e
     * @param item
     */
    poiLocation(e, item) {
      poiAddress({ _id: item.id }).then(async res => {
        const mapModuleIndex = this.mapModuleIndex;
        const maps = await this.mapService.getMap();
        switch (mapModuleIndex) {
          case 0:
          case 2:
            this.mapService.addMarker([
              parseFloat(res.data.gpsx),
              parseFloat(res.data.gpsy)
            ]);
            if (this.sceneViewer) {
              if (this.sceneViewer.entities.getById("position")) {
                this.sceneViewer.entities.removeById("position");
              }

              const positions = Cesium.Cartographic.fromDegrees(
                res.data.gpsx,
                res.data.gpsy
              );

              const promise = Cesium.sampleTerrain(
                this.sceneViewer.terrainProvider,
                13,
                [positions]
              );

              Cesium.when(promise, updatedPositions => {
                const terrainHeight = updatedPositions[0].height;
                this.sceneViewer.entities.add({
                  id: "position",
                  position: Cesium.Cartesian3.fromDegrees(
                    res.data.gpsx,
                    res.data.gpsy,
                    terrainHeight + 10
                  ),
                  billboard: {
                    image: "/static/img/milSearch/location.png",
                    verticalOrigin: Cesium.VerticalOrigin.TOP
                  }
                });
              });
            }
            break;
          case 1:
            if (this.sceneViewer.entities.getById("position")) {
              this.sceneViewer.entities.removeById("position");
            }

            const positionsa = Cesium.Cartographic.fromDegrees(
              res.data.gpsx,
              res.data.gpsy
            );

            const promisea = Cesium.sampleTerrain(
              this.sceneViewer.terrainProvider,
              13,
              [positionsa]
            );

            Cesium.when(promisea, updatedPositions => {
              const terrainHeight = updatedPositions[0].height;
              this.sceneViewer.entities.add({
                id: "position",
                position: Cesium.Cartesian3.fromDegrees(
                  res.data.gpsx,
                  res.data.gpsy,
                  terrainHeight + 10
                ),
                billboard: {
                  image: "/static/img/milSearch/location.png",
                  verticalOrigin: Cesium.VerticalOrigin.TOP
                }
              });
            });

            this.sceneViewer.camera.flyTo({
              destination: Cesium.Cartesian3.fromDegrees(
                res.data.gpsx,
                res.data.gpsy,
                2000
              ),
              duration: 3,
              orientation: {
                heading: 6.283185307179586,
                pitch: -1.5707963267948966,
                roll: 0
              }
            });

            break;
        }
      });
    },

    riverLocation(e, item) {},

    /**
     * 获取书签列表
     */
    getBookMarks() {
      const mapModuleIndex = this.mapModuleIndex;
      switch (mapModuleIndex) {
        case 0:
          list({ type: 0, uid: this.$store.getters.id }).then(res => {
            this.bookmarks = res.data;
          });
          break;
        case 1:
          list({ type: 1, uid: this.$store.getters.id }).then(res => {
            this.bookmarks = res.data;
          });
          break;
        case 2:
          list({ type: 0, uid: this.$store.getters.id }).then(res => {
            this.bookmarks = res.data;
          });
          break;
      }
    },
    /**
     * 提交
     */
    handleConfirm() {
      if (this.isAdd) {
        add(this.form).then(res => {
          this.bookmarks.push(res.data);
          this.dialogFormVisible = false;
        });
      } else {
        update(this.form).then(res => {
          const index = this.bookmarks.findIndex(o => o._id === this.form._id);
          this.bookmarks.splice(index, 1, this.form);
          this.dialogFormVisible = false;
        });
      }
    },
    /**
     * 删除书签
     * @param item
     */
    handleDelete(item) {
      this.$confirm("此操作将永久删除该记录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          remove(item).then(res => {
            this.bookmarks.splice(this.bookmarks.indexOf(item), 1);
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    /**
     * 编辑书签
     * @param item
     */
    handleEdit(item) {
      this.form = Clone.clone(item);
      this.dialogFormVisible = true;
      this.isAdd = false;
    },
    /**
     * 书签定位
     * @param item
     */
    locateTo(item) {
      const mapModuleIndex = this.mapModuleIndex;
      switch (mapModuleIndex) {
        case 0:
        case 2:
          // const map = this.mapService.getMap();
          const map = this.comparable.getMap();
          map.flyTo({
            center: item.camera.center,
            zoom: item.camera.zoom,
            bearing: item.camera.bear,
            pitch: item.camera.pitch,
            duration: 3000,
            speed: 0.2,
            curve: 1
          });
          break;
        case 1:
          const lat = Cesium.Math.toDegrees(item.camera.position.latitude);
          const log = Cesium.Math.toDegrees(item.camera.position.longitude);
          const alt = item.camera.position.height;
          this.sceneViewer.camera.flyTo({
            destination: Cesium.Cartesian3.fromDegrees(log, lat, alt),
            duration: 3,
            orientation: {
              heading: item.camera.heading,
              pitch: item.camera.pitch,
              roll: item.camera.roll
            }
          });
          break;
      }
    },

    /**
     * 二三维切换
     * @param event
     * @param index
     */
    switchMapModule(event, index) {
      this.$store.commit("xcgl/setSwitchMapModuleIndex", index);
      this.getBookMarks();
      this.isVisible = 0;
      this.$nextTick(() => {
        const ev = new Event("resize", { bubbles: true, cancelable: false });
        window.dispatchEvent(ev);
      });
    },

    /**
     * 系统全屏
     */
    appFullScreen() {
      if (document.fullscreenElement) {
        // 存在全屏状态下的节点
        if (document.exitFullscreen) {
          document.exitFullscreen();
        } else if (document.msExitFullscreen) {
          document.msExitFullscreen();
        } else if (document.mozCancelFullScreen) {
          document.mozCancelFullScreen();
        } else if (document.webkitExitFullscreen) {
          document.webkitExitFullscreen();
        }
      } else {
        if (document.documentElement.requestFullscreen) {
          document.documentElement.requestFullscreen();
        } else if (document.documentElement.mozRequestFullScreen) {
          document.documentElement.mozRequestFullScreen();
        } else if (document.documentElement.msRequestFullscreen) {
          document.documentElement.msRequestFullscreen();
        } else if (document.documentElement.webkitRequestFullscreen) {
          document.documentElement.webkitRequestFullscreen();
        }
      }
    },

    /**
     * 回正
     */
    rotateNorth() {
      const scene = this.sceneViewer.scene;
      scene.camera.flyTo({
        destination: scene.camera.position,
        orientation: {
          heading: Cesium.Math.toRadians(0)
        }
      });
    },

    /**
     * 重置回到地球
     */
    goEarch() {
      this.sceneViewer.camera.flyTo({
        destination: new Cesium.Cartesian3.fromDegrees(
          110.60396458865515,
          34.54408834959379,
          30644793.325518917
        ),
        duration: 5
      });
    },

    /**
     * 绕物旋转
     */
    rotateEarch() {
      this.rotate = !this.rotate;
      if (this.rotate) {
        this.sceneTool.Spin();
      } else {
        this.sceneTool.cancelSpin();
      }
    },

    /**
     * 地形夸张改变数值
     */
    altitudeChange($event) {
      this.sceneViewer.scene.terrainExaggeration = $event;
    },

    /**
     * 地形夸张
     */
    altitudeEx($event) {
      this.isVisible = this.isVisible === 8 ? 0 : 8;
    }
  },
  computed: {
    ...mapState({
      isSelect(state) {
        return state.hzzSys.isSelected;
      },
      // 底图分组
      baseMapGroup(state) {
        return state.user.baseGroup;
      },
      // 默认显示图层
      baseLayers(state) {
        return state.user.baseLayers;
      },

      baseLayers_3D(state) {
        return state.user.baseLayers_3D;
      },

      baseMapGroup_3D(state) {},

      // 地图模块控件
      mapModuleIndex(state) {
        return state.xcgl.mapModuleIndex;
      },

      mapService(state) {
        return state.xcgl.mapService;
      },

      sceneViewer(state) {
        return state.xcgl.sceneViewer;
      },

      sceneTool(state) {
        return state.xcgl.sceneTool;
      },
      displayStaticPanelIsShow(state) {
        return state.hzzSys.displayStaticPanelIsShow;
      },

      // --------------------------双屏需要用到的------------------------------
      /**
       * 同步测量
       * @param state
       * @returns {measureSync|(function(*))|*}
       */
      measureSync(state) {
        return state.xcgl.measureSync;
      },

      /**
       * 比较
       * @param state
       * @returns {comparable|(function(*))|*}
       */
      comparable: function(state) {
        return state.xcgl.comparable;
      }
    }),
    // 书签是否有数据
    hasData() {
      return this.bookmarks.length > 0;
    }
  },
  beforeDestroy() {
    // this.mapService.off("map.init", this.mapInitComplete);
    // this.baseMapGroup.forEach((group, i) => {
    //   this.$set(group, "checked", i === 0);
    // });
  },
  watch: {
    isVisible: function(n, o) {
      if (n == 0 && o === 2) {
        // 关闭搜索
        this.mapService.removeMarker();
        if (this.mapModuleIndex === 1 || this.mapModuleIndex === 2) {
          if (
            this.sceneViewer &&
            this.sceneViewer.entities.getById("position")
          ) {
            this.sceneViewer.entities.removeById("position");
          }
        }
      }

      if (n == 0 && o === 6) {
        // 关闭高亮
        this.mapService.setHightLihgtFilter(this.riverLayerName, "");
        if (this.mapModuleIndex === 1 || this.mapModuleIndex === 2) {
          if (
            this.sceneViewer &&
            this.sceneViewer.entities.getById("highRiver")
          ) {
            this.sceneViewer.entities.removeById("highRiver");
          }
        }
      }
    }
  }
};
</script>
<style scoped>
.mapToolbar .mapToolbar-btnGroup {
  position: absolute;
  top: 20px;
  right: 15px;
  z-index: 200;
  cursor: pointer;
}

#nav {
  line-height: 31px;
  list-style-type: none;
  margin: 0;
}

#nav a {
  display: block;
  width: 78px;
  text-align: center;
  color: #fff;
}

#nav a:link {
  color: #fff;
  text-decoration: none;
}

#nav a:visited {
  color: #fff;
  text-decoration: none;
  background: #1884c6;
}

#nav a:hover {
  color: #fff;
  text-decoration: none;
  width: 78px;
}

#nav li {
  float: left;
  width: 80px;
  background: #1884c6;
  color: #fff;
}
.li-one-first {
  border-top-left-radius: 3px;
  border-bottom-left-radius: 5px;
  border-top: 1px solid #fff;
  border-left: 1px solid #fff;
  border-bottom: 1px solid #fff;
}
.li-one-middle {
  border-top: 1px solid #fff;
  border-left: 1px solid #fff;
  border-bottom: 1px solid #fff;
}
.li-one-last {
  border-top-right-radius: 3px;
  border-bottom-right-radius: 3px;
  border: 1px solid #fff;
}
#nav li a:hover {
  background: #0f6598;
  width: 78px;
}

#nav li ul {
  margin-top: 1px;
  line-height: 31px;
  list-style-type: none;
  text-align: left;
  left: -999em;
  width: 80px;
  position: absolute;
}

#nav li ul li {
  float: left;
  background: #1884c6;
  width: 80px;
}

.li-two-first {
  border-left: 1px solid #fff;
  border-right: 1px solid #fff;
  border-bottom: 1px solid #fff;
}
.li-two-third {
  border: 1px solid #fff;
}

.li-two-second {
  border-left: 1px solid #fff;
  border-right: 1px solid #fff;
}

#nav li ul a {
  display: block;
  width: 78px;
  text-align: center;
  overflow: hidden;
}

#nav li ul a:link {
  color: #fff;
  text-decoration: none;
}

#nav li ul a:visited {
  color: #fff;
  text-decoration: none;
}

#nav li ul a:hover {
  color: #fff;
  text-decoration: none;
  background: #0f6598;
  width: 78px;
}

#nav li[class="li-one-first"]:hover ul {
  left: 0;
}

#nav li[class="li-one-last"]:hover ul {
  left: 240px;
}

/* #nav li:hover ul[id='s'] {
  right: 0;
} */

#nav li.sfhover ul {
  left: auto;
}
</style>

